<?php

class Damages_UploadController extends Zend_Controller_Action {

  public function init() {
    $this->_helper->layout->disableLayout();
    $action = $this->getRequest()->getActionName();
    $this->_helper->viewRenderer->setNoRender(true);
    $this->_helper->contextSwitch()
            ->addActionContext($action, 'json')
            ->setAutoJsonSerialization(true)
            ->initContext('json');
    $this->getRequest()->setParam('format', 'json');
  }

  public function indexAction() {
    $type = $this->getRequest()->getParam('type');
    switch ($type) {
      case DamagesDictAttachmentTypes::CODE_LETTER;
        break;
      case DamagesDictAttachmentTypes::CODE_PROTOCOL;
        break;
      case DamagesDictAttachmentTypes::CODE_PHOTO;
        break;
      case DamagesDictAttachmentTypes::CODE_ADDITIONAL;
        break;
      case DamagesDictAttachmentTypes::CODE_ESTIMATED_COSTS;
        break;
      default:
        return;
        break;
    }
    $dictId = DamagesDictAttachmentTypesQuery::create()->findOneByCode($type)->getId();


    $storeFolder = Damages_Config::getInstance()->uploads->mainPath . Damages_Config::getInstance()->uploads->subdirs->tmp;
    if (!empty($_FILES)) {
      $tempFile = $_FILES['file']['tmp_name'];          //3             
      $targetPath = APPLICATION_PATH . '/../public' . $storeFolder;  //4
      if (!is_dir($targetPath))
        mkdir($targetPath, 0777, true);
      $systemFileName = md5($_FILES['file']['name'] . rand() . microtime()) . Core_Tools::getFileExtension($_FILES['file']['name']);
      $targetFile = $targetPath . $systemFileName;  //5
      move_uploaded_file($tempFile, $targetFile); //6
      $dbAtt = new DamagesAttachments();
      $dbAtt->setDictAttachmentTypeId($dictId);
      $dbAtt->setName($_FILES['file']['name']);
      $dbAtt->setFilePath($storeFolder.$systemFileName);
      $dbAtt->save();

      $this->view->type = $type;
      $this->view->dbId = $dbAtt->getId();
    }
    
  }

}